package com.newtouch.avmarketing.mgr.modules.avmarkrting.service.impl;

import com.newtouch.avmarketing.mgr.modules.avmarkrting.service.OcrCardService;
import com.newtouch.avmarketing.mgr.modules.avmarkrting.util.ConstantPropertiesUtil;
import com.newtouch.avmarketing.mgr.modules.avmarkrting.util.FileUtil;
import com.newtouch.avmarketing.mgr.modules.avmarkrting.util.HttpUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Service
public class OcrCardServiceImpl implements OcrCardService {
    @Override
    public String ocrCard(String filePath) throws IOException {
        Map<String, String> header = buildHttpHeader();
        byte[] imageByteArray = FileUtil.read(filePath);
        String imageBase64 = new String(Base64.encodeBase64(imageByteArray), "UTF-8");
        String result = HttpUtil.doPost1(ConstantPropertiesUtil.WEBOCR_URL, header, "image=" + URLEncoder.encode(imageBase64, "UTF-8"));
        return result;
    }

    /**
     * 组装http请求头
     */
    private static Map<String, String> buildHttpHeader() throws UnsupportedEncodingException {
        String curTime = System.currentTimeMillis() / 1000L + "";
        String param = "{\"engine_type\":\"" + ConstantPropertiesUtil.ENGINE_TYPE + "\"}";
        String paramBase64 = new String(Base64.encodeBase64(param.getBytes("UTF-8")));
        String checkSum = DigestUtils.md5Hex(ConstantPropertiesUtil.API_KEY + curTime + paramBase64);
        Map<String, String> header = new HashMap<String, String>();
        header.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        header.put("X-Param", paramBase64);
        header.put("X-CurTime", curTime);
        header.put("X-CheckSum", checkSum);
        header.put("X-Appid", ConstantPropertiesUtil.APPID);
        return header;
    }
}
